package com.zzmcc.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.XStream;
import com.zzmcc.wechat.InstanceFactory;
import com.zzmcc.wechat.bean.InMessage;
import com.zzmcc.wechat.bean.OutMessage;
import com.zzmcc.wechat.entity.Articles;
import com.zzmcc.wechat.service.MessageProcessingHandler;
import com.zzmcc.wechat.service.WechatService;
import com.zzmcc.wechat.util.HttpKit;
import com.zzmcc.wechat.util.XStreamFactory;
import org.smart4j.framework.tx.annotation.Service;
import org.smart4j.framework.util.CastUtil;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;

/**
 * Created by joinwin on 14-7-11.
 */
@Service
public class WechatServiceImpl implements WechatService {

    private static final String ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    @Override
    public  String processing(String responseInputString,String msgHandler) {
        InMessage inMessage = parsingInMessage(responseInputString);
        OutMessage oms = null;
        String xml = "";
        try {
            // 加载处理器
            MessageProcessingHandler messageProcessingHandler = InstanceFactory.getMessageProcessingHandler(msgHandler);
            //取得消息类型
            oms = messageProcessingHandler.getOutMessage(inMessage);
            if(oms != null){
                setMsgInfo(oms, inMessage);
                // 把发送发送对象转换为xml输出
                XStream xs = XStreamFactory.init(true);
                xs.alias("xml", oms.getClass());
                xs.alias("item", Articles.class);
                xml = xs.toXML(oms);
            }
            //调用事后处理
            messageProcessingHandler.afterProcess(inMessage,oms);
            return xml;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void setMsgInfo(OutMessage oms, InMessage msg) {
        try {
            Class<?> outMsg = oms.getClass().getSuperclass();
            Field CreateTime = outMsg.getDeclaredField("CreateTime");
            Field ToUserName = outMsg.getDeclaredField("ToUserName");
            Field FromUserName = outMsg.getDeclaredField("FromUserName");

            ToUserName.setAccessible(true);
            CreateTime.setAccessible(true);
            FromUserName.setAccessible(true);

            CreateTime.set(oms, new Date().getTime());
            ToUserName.set(oms, msg.getFromUserName());
            FromUserName.set(oms, msg.getToUserName());
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    @Override
    public InMessage parsingInMessage(String responseInputString) {
        //转换微信post过来的xml内容
        XStream xs = XStreamFactory.init(false);
        xs.ignoreUnknownElements();
        xs.alias("xml", InMessage.class);
        InMessage msg = (InMessage) xs.fromXML(responseInputString);
        return msg;
    }

    @Override
    public String getAccessToken(String appid, String secret) {

        String jsonStr = HttpKit.get(ACCESSTOKEN_URL.concat("&appid=") + appid + "&secret=" + secret);
        Map<String, Object> map = JSONObject.parseObject(jsonStr);
        return CastUtil.castString( map.get("access_token"));
    }


}
